package com.knight.mybatis.test;

import cn.hutool.json.JSONUtil;
import com.knight.mybatis.example.entity.Comment;
import com.knight.mybatis.example.entity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MybatisTester {

    /**
     * 不创建Mapper
     * @throws IOException
     */
    @Test
    public  void t1() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
            Student one = (Student)sqlSession.selectOne("com.knight.mybatis.example.mapper.StudentMapper.selectStudent", 33);
            System.out.println("[t1]"+one.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 添加示例
     * @throws IOException
     */
    @Test
    public  void t3() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try(SqlSession sqlSession = sqlSessionFactory.openSession()){
            Student student = new Student();
            student.setAge(11);
            student.setName("lisi");
            Comment comment = new Comment();
            comment.setId(1);
            comment.setContent("content");
            student.setComment(comment);
            int num = sqlSession.insert("com.knight.mybatis.example.mapper.StudentMapper.inserStudent", student);
            System.out.println(num);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void  t2(){
        Comment comment = new Comment();
        comment.setId(1);
        comment.setContent("123");

        System.out.println(JSONUtil.toJsonStr(comment));
        String jsonStr = "{\"content\":\"123\",\"id\":1}";
        Comment bean = JSONUtil.toBean(jsonStr, Comment.class);
    }

}
